<template>
  <div class="medical-video-hub" :data-standalone="isStandalone">
    <!-- 独立模式下显示自定义标题 - 这里完全移除标题栏 -->
    <!-- 只保留一个隐藏的传输按钮，可通过键盘快捷键触发 -->
    <div v-if="isStandalone" class="floating-actions">
      <el-button type="primary" circle size="small" @click="showTransferPanel" title="打开传输面板">
        <el-icon><upload-filled /></el-icon>
      </el-button>
    </div>

    <!-- 整体布局 -->
    <el-container>
      <!-- 左侧菜单 -->
      <el-aside width="200px" class="left-menu">
        <h3 class="menu-title">疾病分类</h3>
        <el-menu :default-active="activeCategory" class="category-menu" @select="handleCategorySelect">
          <el-menu-item v-for="category in categories" :key="category.path" :index="category.path">
            {{ category.name }}
          </el-menu-item>
        </el-menu>
      </el-aside>

      <!-- 主内容区 -->
      <el-container>
        <!-- 顶部菜单 - 在独立模式下完全隐藏 -->
        <template v-if="!isStandalone">
          <el-header height="60px" class="top-menu">
            <el-menu :default-active="activeSubCategory" class="subcategory-menu" mode="horizontal"
              @select="handleSubCategorySelect">
              <el-menu-item v-for="subCategory in subCategories" :key="subCategory.path" :index="subCategory.path">
                {{ subCategory.name }}
              </el-menu-item>
            </el-menu>
          </el-header>
        </template>

        <!-- 在独立模式下使用二级侧边栏显示子分类 -->
        <template v-if="isStandalone && subCategories.length > 0">
          <el-aside width="180px" class="sub-category-menu">
            <h3 class="menu-title">{{ currentCategory.name || '子分类' }}</h3>
            <el-menu :default-active="activeSubCategory" class="category-menu" @select="handleSubCategorySelect">
              <el-menu-item v-for="subCategory in subCategories" :key="subCategory.path" :index="subCategory.path">
                {{ subCategory.name }}
              </el-menu-item>
            </el-menu>
          </el-aside>
        </template>

        <!-- 内容区 -->
        <el-main>
          <div v-if="loading" class="loading-container">
            <el-skeleton :rows="10" animated />
          </div>
          <div v-else>
            <!-- 显示当前路径 -->
            <div class="current-path">
              <el-breadcrumb separator="/">
                <el-breadcrumb-item>{{ currentCategory.name }}</el-breadcrumb-item>
                <el-breadcrumb-item>{{ currentSubCategory.name }}</el-breadcrumb-item>
                <el-breadcrumb-item v-if="currentPerson">{{ currentPerson.name }}</el-breadcrumb-item>
              </el-breadcrumb>
            </div>

            <!-- 专家/患者列表区域 -->
            <div v-if="personList.length > 0" class="person-grid">
              <div v-for="person in personList" :key="person.path" class="person-card"
                :class="{ active: currentPerson && currentPerson.path === person.path }"
                @click="handlePersonSelect(person)">
                <el-avatar :size="100" :src="person.avatarUrl || defaultAvatar" @error="handleAvatarError(person)">
                  <img :src="defaultAvatar" />
                </el-avatar>
                <div class="person-name">{{ person.name }}</div>
              </div>
            </div>

            <!-- 视频列表区域 -->
            <div class="video-list">
              <h3 v-if="currentPerson">{{ currentPerson.name }}的视频</h3>
              <h3 v-else-if="personList.length === 0">{{ currentSubCategory.name }}的视频</h3>

              <el-empty v-if="videos.length === 0" description="暂无视频"></el-empty>

              <div v-else class="video-grid">
                <div class="video-card" v-for="video in videos" :key="video.path">
                  <div class="video-thumbnail" @click="previewVideo(video)">
                    <video-thumbnail :video-url="video.url" :thumbnail-url="video.thumbnailUrl" />
                  </div>
                  <div class="video-info">
                    <div class="video-title" @click="previewVideo(video)">{{ video.name }}</div>
                    <div class="video-size">{{ formatFileSize(video.size) }}</div>
                    <div class="video-actions">
                      <el-button type="primary" size="small" @click="previewVideo(video)">播放</el-button>
                      <el-button size="small" @click="downloadVideo(video)">下载</el-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-main>
      </el-container>
    </el-container>

    <!-- 视频预览对话框 -->
    <el-dialog v-model="videoDialogVisible" title="视频播放" width="70%" :before-close="closeVideoDialog">
      <div v-if="currentVideo" class="video-player-container">
        <h3>{{ currentVideo.name }}</h3>
        <video controls autoplay class="video-player" :src="currentVideo.url"></video>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useRoute } from 'vue-router';
import { UploadFilled } from '@element-plus/icons-vue';
import VideoThumbnail from '../components/VideoThumbnail.vue';
import defaultAvatarImg from '../assets/default-avatar.png'; // 导入默认头像

// 使用导入的图片
const defaultAvatar = defaultAvatarImg;

// 检测是否在独立模式下运行
const route = useRoute();
const isStandalone = computed(() => {
  return route.name === 'medical-standalone';
});

// 添加键盘事件监听器
onMounted(() => {
  fetchCategories();

  // 为独立模式添加键盘快捷键
  if (isStandalone.value) {
    window.addEventListener('keydown', handleKeyDown);
  }
});

// 在组件卸载时移除事件监听器
const handleKeyDown = (event) => {
  // 按T键打开传输面板
  if (event.key === 't' || event.key === 'T') {
    showTransferPanel();
  }
};

// 显示传输面板
const showTransferPanel = () => {
  if (window.transferManager && typeof window.transferManager.showPanel === 'function') {
    window.transferManager.showPanel();
  } else if (window.transferManager && typeof window.transferManager.showTransferPanel === 'function') {
    window.transferManager.showTransferPanel();
  } else {
    console.error('无法显示传输面板：找不到transferManager');
  }
};

// 状态管理
const loading = ref(true);
const categories = ref([]);
const subCategories = ref([]);
const personList = ref([]);
const videos = ref([]);
const activeCategory = ref('');
const activeSubCategory = ref('');
const currentPerson = ref(null);
const videoDialogVisible = ref(false);
const currentVideo = ref(null);

// 计算当前选中的分类和子分类
const currentCategory = computed(() => {
  return categories.value.find(c => c.path === activeCategory.value) || {};
});

const currentSubCategory = computed(() => {
  return subCategories.value.find(c => c.path === activeSubCategory.value) || {};
});

// 页面加载时获取一级目录
onMounted(async () => {
  await fetchCategories();
});

// 监听一级目录变化，加载二级目录
watch(activeCategory, async (newValue) => {
  if (newValue) {
    await fetchSubCategories(newValue);
  }
});

// 监听二级目录变化，加载人物列表或视频
watch(activeSubCategory, async (newValue) => {
  if (newValue) {
    currentPerson.value = null;
    await fetchContent(newValue);
  }
});

// 监听人物选择变化，加载视频
watch(currentPerson, async (newValue) => {
  if (newValue) {
    await fetchVideos(newValue.path);
  }
});

// 获取一级目录（疾病分类）
const fetchCategories = async () => {
  loading.value = true;
  try {
    const response = await axios.get('/api/cos/list', {
      params: { prefix: '' }
    });

    if (response.data.success) {
      // 只过滤出文件夹类型作为一级分类，排除thumbnail文件夹
      categories.value = response.data.data
        .filter(item => item.type === 'folder' && item.name !== 'thumbnail')
        .map(folder => ({
          name: folder.name,
          path: folder.key
        }));

      if (categories.value.length > 0) {
        activeCategory.value = categories.value[0].path;
      }
    } else {
      ElMessage.error('获取分类失败');
    }
  } catch (error) {
    console.error('获取分类失败:', error);
    ElMessage.error('获取分类失败');
  } finally {
    loading.value = false;
  }
};

// 获取二级目录（专家、患者、讲座）
const fetchSubCategories = async (categoryPath) => {
  loading.value = true;
  try {
    const response = await axios.get('/api/cos/list', {
      params: { prefix: categoryPath }
    });

    if (response.data.success) {
      // 只过滤出文件夹类型作为二级分类，排除thumbnail文件夹
      subCategories.value = response.data.data
        .filter(item => item.type === 'folder' && item.name !== 'thumbnail')
        .map(folder => ({
          name: folder.name,
          path: folder.key
        }));

      if (subCategories.value.length > 0) {
        activeSubCategory.value = subCategories.value[0].path;
      } else {
        activeSubCategory.value = '';
        personList.value = [];
        videos.value = [];
      }
    } else {
      ElMessage.error('获取子分类失败');
    }
  } catch (error) {
    console.error('获取子分类失败:', error);
    ElMessage.error('获取子分类失败');
  } finally {
    loading.value = false;
  }
};

// 获取内容（人物列表或直接视频）
const fetchContent = async (subCategoryPath) => {
  loading.value = true;
  personList.value = [];
  videos.value = [];

  try {
    console.log('获取目录内容:', subCategoryPath);
    const response = await axios.get('/api/cos/list', {
      params: { prefix: subCategoryPath }
    });

    if (response.data.success) {
      console.log('目录内容获取成功, 数据:', response.data);
      const items = response.data.data;

      // 检查是否有文件夹（表示有人物目录），排除thumbnail文件夹
      const folders = items.filter(item => item.type === 'folder' && item.name !== 'thumbnail');
      console.log('过滤后的人物文件夹:', folders.map(f => f.name));

      if (folders.length > 0) {
        // 有人物目录，显示人物列表
        // 使用Promise.all并行加载每个人物的头像
        const personListPromises = folders.map(async (folder) => {
          let avatarUrl = null;
          console.log(`查找 ${folder.name} 的头像...`);

          // 先查找当前目录中是否有同名头像
          const avatarFileInCurrentDir = items.find(item =>
            (item.type === 'file' || item.type === 'image') && // 同时接受'file'和'image'类型
            (item.name === `${folder.name}.png` || item.name === `${folder.name}.jpg` || item.name === `${folder.name}.jpeg`)
          );

          if (avatarFileInCurrentDir) {
            console.log(`在当前目录找到 ${folder.name} 的头像:`, avatarFileInCurrentDir.name);
            avatarUrl = avatarFileInCurrentDir.url;
          } else {
            console.log(`当前目录未找到 ${folder.name} 的头像，尝试查找子目录...`);
            // 如果当前目录没有，查找子目录中是否有同名头像
            try {
              const subDirResponse = await axios.get('/api/cos/list', {
                params: { prefix: folder.key }
              });

              if (subDirResponse.data.success) {
                console.log(`获取子目录 ${folder.key} 内容成功:`, subDirResponse.data);
                const subDirItems = subDirResponse.data.data;

                console.log(`在子目录中查找 ${folder.name}.png 或 ${folder.name}.jpg...`);
                for (const item of subDirItems) {
                  console.log(`检查文件: ${item.name}, 类型: ${item.type}`);
                }

                const avatarFileInSubDir = subDirItems.find(item =>
                  (item.type === 'file' || item.type === 'image') && // 同时接受'file'和'image'类型
                  (item.name === `${folder.name}.png` || item.name === `${folder.name}.jpg` || item.name === `${folder.name}.jpeg`)
                );

                if (avatarFileInSubDir) {
                  console.log(`在子目录找到 ${folder.name} 的头像:`, avatarFileInSubDir.name);
                  avatarUrl = avatarFileInSubDir.url;
                } else {
                  console.log(`子目录中未找到 ${folder.name} 的头像`);

                  // 额外尝试查找任何以png、jpg结尾的图片作为头像
                  const anyImageFile = subDirItems.find(item =>
                    (item.type === 'file' || item.type === 'image') && // 同时接受'file'和'image'类型
                    (item.name.endsWith('.png') || item.name.endsWith('.jpg') || item.name.endsWith('.jpeg'))
                  );

                  if (anyImageFile) {
                    console.log(`使用子目录中发现的其他图片作为头像:`, anyImageFile.name);
                    avatarUrl = anyImageFile.url;
                  }
                }
              }
            } catch (error) {
              console.error(`获取子目录内容失败: ${folder.key}`, error);
            }
          }

          console.log(`${folder.name} 最终头像URL:`, avatarUrl);
          return {
            name: folder.name,
            path: folder.key,
            avatarUrl: avatarUrl
          };
        });

        personList.value = await Promise.all(personListPromises);
        console.log('最终生成的人物列表:', personList.value);

        // 默认选中第一个人物
        if (personList.value.length > 0) {
          currentPerson.value = personList.value[0];
          console.log('默认选中人物:', currentPerson.value);
        }
      } else {
        // 没有人物目录，直接显示视频
        videos.value = items
          .filter(item => (item.type === 'file' || item.type === 'video') && isVideoFile(item.name))
          .map(file => ({
            name: file.name,
            path: file.key,
            url: file.url,
            size: file.size,
            thumbnailUrl: file.thumbnailUrl
          }));
        console.log('直接显示视频，数量:', videos.value.length);
      }
    } else {
      console.error('获取内容失败:', response.data);
      ElMessage.error('获取内容失败');
    }
  } catch (error) {
    console.error('获取内容失败:', error);
    ElMessage.error('获取内容失败');
  } finally {
    loading.value = false;
  }
};

// 获取人物下的视频
const fetchVideos = async (personPath) => {
  loading.value = true;
  videos.value = [];

  try {
    console.log('获取视频列表:', personPath);
    const response = await axios.get('/api/cos/list', {
      params: { prefix: personPath }
    });

    if (response.data.success) {
      console.log('视频列表获取成功:', response.data);
      // 记录所有项目以便调试
      response.data.data.forEach(item => {
        console.log(`文件: ${item.name}, 类型: ${item.type}`);
      });

      videos.value = response.data.data
        .filter(item => (item.type === 'file' || item.type === 'video') && isVideoFile(item.name))
        .map(file => ({
          name: file.name,
          path: file.key,
          url: file.url,
          size: file.size,
          thumbnailUrl: file.thumbnailUrl
        }));

      console.log('过滤后的视频列表:', videos.value);
    } else {
      ElMessage.error('获取视频失败');
    }
  } catch (error) {
    console.error('获取视频失败:', error);
    ElMessage.error('获取视频失败');
  } finally {
    loading.value = false;
  }
};

// 处理分类选择
const handleCategorySelect = (key) => {
  activeCategory.value = key;
};

// 处理子分类选择
const handleSubCategorySelect = (key) => {
  activeSubCategory.value = key;
};

// 处理人物选择
const handlePersonSelect = (person) => {
  currentPerson.value = person;
};

// 预览视频
const previewVideo = (video) => {
  currentVideo.value = video;
  videoDialogVisible.value = true;
};

// 关闭视频对话框
const closeVideoDialog = () => {
  videoDialogVisible.value = false;
  currentVideo.value = null;
};

// 下载视频
const downloadVideo = (video) => {
  if (window.transferManager && typeof window.transferManager.addTask === 'function') {
    const taskId = window.transferManager.addTask({
      fileName: video.name,
      type: 'download',
      totalSize: video.size,
      progress: 0,
      status: 'waiting'
    });

    // 显示传输面板
    if (typeof window.transferManager.showPanel === 'function') {
      window.transferManager.showPanel();
    }

    // 执行下载
    const link = document.createElement('a');
    link.href = video.url;
    link.download = video.name;
    link.target = '_blank';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    // 更新传输任务进度
    if (taskId && typeof window.transferManager.updateTask === 'function') {
      // 由于无法跟踪浏览器下载进度，简单地标记为完成
      setTimeout(() => {
        window.transferManager.completeTask(taskId, true);
      }, 2000);
    }
  } else {
    // 降级方案：直接下载
    window.open(video.url, '_blank');
  }
};

// 工具函数：检查是否为视频文件
const isVideoFile = (filename) => {
  const videoExtensions = ['.mp4', '.avi', '.mov', '.wmv', '.flv', '.mkv', '.webm', '.m4v'];
  const lowerFilename = filename.toLowerCase();
  const isVideo = videoExtensions.some(ext => lowerFilename.endsWith(ext));
  console.log(`检查文件 ${filename} 是否为视频: ${isVideo}`);
  return isVideo;
};

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

// 处理头像加载错误
const handleAvatarError = (person) => {
  console.error(`头像加载失败: ${person.name}`, {
    头像URL: person.avatarUrl,
    默认头像: defaultAvatar
  });
  // 返回false表示不阻止默认错误处理
  return false;
};

// 日志调试字符串过滤（防止过长）
const trimString = (str, maxLength = 200) => {
  if (!str) return str;
  if (str.length <= maxLength) return str;
  return str.substring(0, maxLength) + '...';
};
</script>

<style scoped>
.medical-video-hub {
  height: 100%;
  width: 100%;
}

/* 独立模式标题样式 */
.standalone-header {
  background-color: #409EFF;
  color: white;
  padding: 0;
  height: 60px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.standalone-header .header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  height: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.site-title {
  font-size: 24px;
  font-weight: bold;
  margin: 0;
}

.left-menu {
  background-color: #f5f7fa;
  border-right: 1px solid #e6e6e6;
  height: 100vh;
  /* 独立模式下占据整个视口高度 */
}

/* 子分类侧边栏样式 */
.sub-category-menu {
  background-color: #f9f9f9;
  border-right: 1px solid #e6e6e6;
  height: 100vh;
}

.menu-title {
  padding: 16px;
  margin: 0;
  border-bottom: 1px solid #e6e6e6;
}

.top-menu {
  border-bottom: 1px solid #e6e6e6;
  padding: 0;
}

.loading-container {
  padding: 20px;
}

.current-path {
  margin-bottom: 20px;
}

.person-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 30px;
}

.person-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 140px;
  height: 160px;
  border: 1px solid #e6e6e6;
  border-radius: 8px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.person-card:hover {
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  transform: translateY(-3px);
}

.person-card.active {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.person-name {
  margin-top: 10px;
  text-align: center;
  font-weight: bold;
}

.video-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.video-card {
  border: 1px solid #e6e6e6;
  border-radius: 8px;
  overflow: hidden;
}

.video-thumbnail {
  width: 100%;
  height: 180px;
  overflow: hidden;
  background-color: #000;
  position: relative;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.video-thumbnail:hover {
  transform: scale(1.02);
}

.video-thumbnail::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
  opacity: 0;
  transition: opacity 0.2s ease;
  pointer-events: none;
}

.video-thumbnail:hover::after {
  opacity: 1;
}

.video-info {
  padding: 10px;
}

.video-title {
  font-weight: bold;
  margin-bottom: 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: pointer;
  transition: color 0.2s ease;
}

.video-title:hover {
  color: #409EFF;
}

.video-size {
  color: #909399;
  font-size: 0.8em;
  margin-bottom: 10px;
}

.video-actions {
  display: flex;
  gap: 10px;
}

.video-player-container {
  width: 100%;
}

.video-player {
  width: 100%;
  max-height: 70vh;
}

/* 添加悬浮按钮样式 */
.floating-actions {
  position: fixed;
  right: 20px;
  bottom: 20px;
  z-index: 1000;
}

/* 当不是独立模式时的顶部菜单样式 */
.top-menu {
  border-bottom: 1px solid #e6e6e6;
  padding: 0;
}

/* 添加独立模式下的内容区样式 */
.el-main {
  padding: 20px;
  overflow-y: auto;
  height: 100vh;
}

/* 在独立模式下确保内容区域撑满 */
:is(.medical-video-hub[data-standalone="true"]) .el-main {
  height: calc(100vh - 40px);
  /* 留出一些底部空间 */
}
</style>